Fork me on GitHub

SpringBoot 配置 Redis

注意:所有文章除特别说明外,转载请注明出处.

SpringBoot集成Redis

概念

在Java中与redis连接的驱动有很多,目前广泛使用的是Jedis,其它的还有Lettuce/Jredis和Srp。Spring提供一种RedisConnectionFactory接口,通过此接口可以生成一个RedisConnection接口对象,而该接口对象是对Redis底层接口的封装。

RedisTemplate

RedisTemplate是一个强大的类,首先会自动从RedisConnectionFactory工厂中获取连接,然后执行对应的Redis命令,在最后还会关闭Redis的连接。这些都被RedisTemplate封装,所以不需要关心Redis连接闭合问题。

1.创建RedisTemplate

使用Java配置文件RedisConfig创建Spring IOC容器,然后从中获取RedisTemplate对象。

@Bean(name="redisTemplate")
public RedisTemplate<Object, Object> initRedisTemplate(){

    RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();

    redisTemplate.setConnectionFactory(initConnectionFactory());
    return redisTemplate;
}

2.测试

public class RedisTest{
    public static void main(String[] args){
        ApplicationContext ctx = new AnnotationConfigApplicationContext(RedisConfig.class);

        RedisTemplate redisTemplate = ctx.getBean(RedisTemplate.class);
        redisTemplate.opsForValue().set("keyOne", "valueOne");
        redisTemplate.opsForHash().put("hash", "field", "hashvalue");
    }
}

在SpringBoot中配置和使用Redis

1.在SpringBoot中配置Redis

#redis属性配置
spring.redis.host=127.0.0.1
## Redis服务器连接端口
spring.redis.port=6379
## 连接超时时间(毫秒)
spring.redis.timeout=3
## Redis服务器连接密码(默认为空)
spring.redis.password=
## 连接池中的最大连接数
spring.redis.poolMaxTotal=10
## 连接池中的最大空闲连接
spring.redis.poolMaxIdle=10
## 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.poolMaxWait=3

提示:在配置连接池和服务器属性之后,SpringBoot的自动装配机制会读取配置生成相关的Redis操作对象。

2.操作Redis数据类型

本文标题:SpringBoot 配置 Redis

文章作者:Bangjin-Hu

发布时间:2019年10月15日 - 09:22:26

最后更新:2020年03月30日 - 08:00:03

原始链接:http://bangjinhu.github.io/undefined/SpringBoot 配置 Redis/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

Bangjin-Hu wechat
欢迎扫码关注微信公众号,订阅我的微信公众号.
坚持原创技术分享,您的支持是我创作的动力.